package pl.uz.zgora.plan;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class KalendarzTypDataSource {

private SQLiteDatabase database;
	
	public KalendarzTypDataSource(SQLiteDatabase database)
	{
		this.database = database;
	}
	
	public boolean addKalendarzInfo(final KalendarzTyp info)
	{
		if(!database.isOpen())
			throw new SQLiteException("Database not open!");
		
		if(database.isReadOnly())
			throw new SQLiteException("Wrong database connection!");
		
		ContentValues values = new ContentValues();
		values.put(PlanDatabaseHandler.KEY_ID, info.getLink());
		values.put(PlanDatabaseHandler.KEY_NAME, info.getNazwa());
		
		if(database.insert(PlanDatabaseHandler.TABLE_KALENDARZ_INFO, null, values) == -1)
			return false;
		
		return true;
	}
	
	public boolean addKalendarzInfoList(final ArrayList<KalendarzTyp> infos)
	{
		if(infos == null || infos.size() == 0)
			throw new IllegalArgumentException("Argument infos jest pusty");
		
		for(KalendarzTyp info: infos)
			if(!addKalendarzInfo(info))
				return false;
		
		return true;
	}
	
	public ArrayList<KalendarzTyp> getKalendarzInfoList()
	{
		if(!database.isOpen())
			throw new SQLiteException("Database not open!");
		
		ArrayList<KalendarzTyp> infos = new ArrayList<KalendarzTyp>();
		Cursor cursor = null;
			
		cursor = database.query(PlanDatabaseHandler.TABLE_KALENDARZ_INFO,
				null, null, null, null, null, null);
	
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			final KalendarzTyp info = cursorToInfo(cursor);
			infos.add(info);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		
		return infos;
	}
	
	public static KalendarzTyp cursorToInfo(Cursor cursor)
	{
		KalendarzTyp info = new KalendarzTyp();
		info.setNazwa(cursor.getString(1));
		info.setLink(cursor.getString(0));
		return info;
	}
}
